package cn.ym.ymcc.service.impl;

import cn.ym.ymcc.domain.Department;
import cn.ym.ymcc.domain.Department;
import cn.ym.ymcc.mapper.DepartmentMapper;
import cn.ym.ymcc.mapper.DepartmentMapper;
import cn.ym.ymcc.query.DepartmentQuery;
import cn.ym.ymcc.result.PageList;
import cn.ym.ymcc.service.IDepartmentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 210513347@qq.com
 * @since 2023-05-04
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public PageList<Department> queryPage(DepartmentQuery query) {
        //1.查询总数量 - 前端计算分页栏
        Long count = departmentMapper.queryCount(query);
        if(count < 1){//没有数据
            return new PageList<>();
        }
        //2.查询当前页的分页数据 - 前端展示当前页的数据
        List<Department> list = departmentMapper.queryData(query);
        return new PageList<>(count,list);
    }

    @Override
    public List<Department> deptTree() {
        //1.先查询出有部门
        List<Department> departments = departmentMapper.selectList(null);
        //2.用一个map来装部门：key：id  value：部门
        Map<Long,Department> map = departments.stream().collect(Collectors.toMap(Department::getId, department -> department));

        //3.用一个list来装课程分类数据
        List<Department> deptTree = new ArrayList<>();
        //4.循环遍历部门集合
        for (Department department : departments) {
            //4.1没有父级id直接装进去
           if ( department.getParentId()==null){
               deptTree.add(department);
           }else {
               //4.2:有父级id装Children进去
               Department  ParentDepartment = map.get(department.getParentId());
                if (department!=null){
                    ParentDepartment.getChildren().add(department);
                }
           }
        }
        return deptTree;
    }
}
